﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PegasCompany.Data;
using PegasCompany.SiteMembership;
using PegasCompany.Tools.Storage;

namespace PegasCompany
{
    public partial class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            MembershipHelper.FormsService.SignOut();
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (!MembershipHelper.RoleService.AdminExists())
            {
                Response.Redirect("/AccountProcessing.aspx?view=Registration&role=admin");
            }
            else
            {
                if (Page.IsValid)
                {
                    string sEmail = txtEmail.Text.Trim();
                    string sPassword = txtPassword.Text.Trim();

                    if (!MembershipHelper.MembershipService.ValidateUser(sEmail, sPassword))
                        return;

                    SiteUser dbuser = SiteUser.SearchByEmail(sEmail);
                    if (dbuser != null && dbuser.UserId != null)
                    {
                        SiteUserExtended siteUser = SiteUserExtended.Get(dbuser.UserId.Value);
                        if (siteUser != null)
                        {
                            SessionHelper.ActiveUser = siteUser;
                            MembershipHelper.FormsService.SignIn(sEmail, false);

                            if (chkRememberMe.Checked)
                                CookieHelper.CookieUser = siteUser;
                        }
                    }

                    Response.Redirect(Request.Url.AbsoluteUri);
                }
            }
        }
    }
}